import Router from 'koa-router';
import { SysAdminRoleService } from '../../service/system/SysAdminRole.js';
import {
  CreateSysAdminRoleDto,
  UpdateSysAdminRoleDto,
  SysAdminRoleQueryDto,
} from '../../entities/system/SysAdminRole.js';
import type { AppContext } from '../../types/index.js';
import { Response } from '../../utils/response.js';
import { BusinessException } from '../../types/exceptions.js';
import { ValidationUtil } from '../../utils/validation.js';

const router = new Router<Record<string, unknown>, AppContext>();

// 使用单例模式，避免重复创建服务实例
class AdminRoleController {
  private static instance: AdminRoleController;
  private readonly adminRoleService: SysAdminRoleService;

  private constructor() {
    this.adminRoleService = new SysAdminRoleService();
  }

  static getInstance(): AdminRoleController {
    if (!AdminRoleController.instance) {
      AdminRoleController.instance = new AdminRoleController();
    }
    return AdminRoleController.instance;
  }

  // 创建管理员角色关联
  async create(ctx: AppContext): Promise<void> {
    const adminRole = ctx.request.body as CreateSysAdminRoleDto;

    // 参数验证
    ValidationUtil.validateId(adminRole.admin_id as number, '管理员ID');
    ValidationUtil.validateId(adminRole.role_id as number, '角色ID');

    const adminRoleId = await this.adminRoleService.create(adminRole);
    ctx.body = Response.success('创建成功', { id: adminRoleId });
  }

  // 获取管理员角色关联列表
  async list(ctx: AppContext): Promise<void> {
    const { page, pageSize, ...query } = ctx.query;
    const { pageNum, pageSizeNum } = ValidationUtil.validatePagination(
      page as string,
      pageSize as string
    );

    const result = await this.adminRoleService.list(
      pageNum,
      pageSizeNum,
      query as SysAdminRoleQueryDto
    );
    ctx.body = Response.success('获取成功', result);
  }

  // 更新管理员角色关联
  async update(ctx: AppContext): Promise<void> {
    const id = ValidationUtil.validateId(ctx.params.id, 'ID');
    const adminRole = ctx.request.body as UpdateSysAdminRoleDto;

    if (Object.keys(adminRole).length === 0) {
      throw new BusinessException('更新数据不能为空');
    }

    const success = await this.adminRoleService.update(id, adminRole);
    if (!success) {
      throw new BusinessException('更新失败，记录不存在或已被删除');
    }

    ctx.body = Response.success('更新成功');
  }

  // 删除管理员角色关联
  async delete(ctx: AppContext): Promise<void> {
    const id = ValidationUtil.validateId(ctx.params.id, 'ID');

    const success = await this.adminRoleService.delete(id);
    if (!success) {
      throw new BusinessException('删除失败，记录不存在或已被删除');
    }

    ctx.body = Response.success('删除成功');
  }

  // 根据ID获取管理员角色关联详情
  async getById(ctx: AppContext): Promise<void> {
    const id = ValidationUtil.validateId(ctx.params.id, 'ID');

    const adminRole = await this.adminRoleService.getById(id);
    if (!adminRole) {
      throw new BusinessException('记录不存在');
    }

    ctx.body = Response.success('获取成功', adminRole);
  }

  // 根据管理员ID获取角色关联
  async getByAdminId(ctx: AppContext): Promise<void> {
    const adminId = ValidationUtil.validateId(ctx.params.adminId, '管理员ID');

    const adminRoles = await this.adminRoleService.getByAdminId(adminId);
    ctx.body = Response.success('获取成功', adminRoles);
  }

  // 根据角色ID获取管理员关联
  async getByRoleId(ctx: AppContext): Promise<void> {
    const roleId = ValidationUtil.validateId(ctx.params.roleId, '角色ID');

    const adminRoles = await this.adminRoleService.getByRoleId(roleId);
    ctx.body = Response.success('获取成功', adminRoles);
  }

  // 删除管理员的所有角色关联
  async deleteByAdminId(ctx: AppContext): Promise<void> {
    const adminId = ValidationUtil.validateId(ctx.params.adminId, '管理员ID');

    const success = await this.adminRoleService.deleteByAdminId(adminId);
    if (!success) {
      throw new BusinessException('删除失败，没有找到相关记录');
    }

    ctx.body = Response.success('删除成功');
  }

  // 删除角色的所有管理员关联
  async deleteByRoleId(ctx: AppContext): Promise<void> {
    const roleId = ValidationUtil.validateId(ctx.params.roleId, '角色ID');

    const success = await this.adminRoleService.deleteByRoleId(roleId);
    if (!success) {
      throw new BusinessException('删除失败，没有找到相关记录');
    }

    ctx.body = Response.success('删除成功');
  }
}

const controller = AdminRoleController.getInstance();

// 路由定义
router.post('/create', (ctx: AppContext) => controller.create(ctx));
router.get('/list', (ctx: AppContext) => controller.list(ctx));
router.put('/:id', (ctx: AppContext) => controller.update(ctx));
router.delete('/:id', (ctx: AppContext) => controller.delete(ctx));
router.get('/:id', (ctx: AppContext) => controller.getById(ctx));
router.get('/admin/:adminId', (ctx: AppContext) => controller.getByAdminId(ctx));
router.get('/role/:roleId', (ctx: AppContext) => controller.getByRoleId(ctx));
router.delete('/admin/:adminId', (ctx: AppContext) => controller.deleteByAdminId(ctx));
router.delete('/role/:roleId', (ctx: AppContext) => controller.deleteByRoleId(ctx));

export default router;
